package com.ny;

import com.ny.until.JwtInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*");
        config.setAllowCredentials(true);
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
    
    /**
     * 注册JWT拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 创建JWT拦截器实例
        JwtInterceptor jwtInterceptor = new JwtInterceptor();
        
        // 注册拦截器并设置拦截路径和排除路径
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/user/**") // 拦截所有以/user开头的请求
                .excludePathPatterns("/login") // 排除登录接口
                .excludePathPatterns("/register") // 排除注册接口
                .excludePathPatterns("/findUserByEmail") // 排除查找用户接口
                .excludePathPatterns("/sendEmail") // 排除发送邮件接口
                .excludePathPatterns("/updatePassword"); // 排除修改密码接口
    }
}
